package com.wehealth.three.lib_connect.utils;


import static com.wehealth.three.lib_connect.utils.ByteDataUtil.toByteArray;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;

import com.wehealth.three.lib_connect.constant.CommonKeyConstant;
import com.wehealth.three.lib_connect.data.ECGData;
import com.wehealth.three.lib_connect.enums.ECGDataDiagnosisType;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

public class EcgFileUtil {
    static SimpleDateFormat sdf_common_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static SimpleDateFormat sdf_simple_format = new SimpleDateFormat("yyyyMMddHHmmss");

    /****
     * 将采集到的心电数据转化为xml文件存储
     * @param context
     * @param listMaps
     * @param ecgDataMaps
     * @return
     */
    public static String saveEcgDataToXMLFile(Context context, Map<String, Map<String, String>> listMaps,
                                              Map<String, String> ecgDataMaps) {
        String path = null;
        try {
            //获取测量用户的信息
            Map<String, String> pInfo = listMaps.get(CommonKeyConstant.ECG_PATIENT_INFO);
            //获取ecg测量的信息
            Map<String, String> ecgAttr = listMaps.get(CommonKeyConstant.ECG_ANALYSE_PARAM);
            //获取测量的时间
            long timeLong = Long.parseLong(pInfo.get("ecg_checktime"));
            String time = sdf_simple_format.format(new Date(timeLong));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                path = context.getExternalFilesDir(CommonKeyConstant.Version_XML) + File.separator + time + ".xml";
            } else {
                File fileDir = new File(Environment.getExternalStorageDirectory() + "/ECGDATA/XML");
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                path = fileDir.getAbsolutePath() + File.separator + time + ".xml";
            }
            FileOutputStream fos = new FileOutputStream(path);
            XmlSerializer serXML = Xml.newSerializer();
            serXML.setOutput(fos, "UTF-8");
            serXML.startDocument("UTF-8", true);
            serXML.startTag(null, "ECG");
            serXML.attribute(null, "Version", ecgAttr.get("AnalysesVersion"));
            serXML.attribute(null, "LS", "12");
            serXML.attribute(null, "FNotch", ecgAttr.get("FilterAC"));
            serXML.attribute(null, "FHP", ecgAttr.get("FilterBase"));
            serXML.attribute(null, "FLP", ecgAttr.get("FilterLP"));
            serXML.startTag(null, "Patient");

            serXML.startTag(null, "Name");
            serXML.text(pInfo.get("Name"));
            serXML.endTag(null, "Name");

            serXML.startTag(null, "ID");
            serXML.text(pInfo.get("ID"));
            serXML.endTag(null, "ID");

            serXML.startTag(null, "Age");
            serXML.text(pInfo.get("AGE"));
            serXML.endTag(null, "Age");

            serXML.startTag(null, "Gender");
            serXML.text(pInfo.get("Gender"));
            serXML.endTag(null, "Gender");
            serXML.startTag(null, "CheckDateTime");
            serXML.text(sdf_common_format.format(new Date(timeLong)));
            serXML.endTag(null, "CheckDateTime");

            serXML.endTag(null, "Patient");
            if (ecgDataMaps != null) {
                serXML.startTag(null, "Ch0");
                serXML.text(ecgDataMaps.get("Ch0"));
                serXML.endTag(null, "Ch0");
                serXML.startTag(null, "Ch1");
                serXML.text(ecgDataMaps.get("Ch1"));
                serXML.endTag(null, "Ch1");
                serXML.startTag(null, "Ch2");
                serXML.text(ecgDataMaps.get("Ch2"));
                serXML.endTag(null, "Ch2");
                serXML.startTag(null, "Ch3");
                serXML.text(ecgDataMaps.get("Ch3"));
                serXML.endTag(null, "Ch3");
                serXML.startTag(null, "Ch4");
                serXML.text(ecgDataMaps.get("Ch4"));
                serXML.endTag(null, "Ch4");
                serXML.startTag(null, "Ch5");
                serXML.text(ecgDataMaps.get("Ch5"));
                serXML.endTag(null, "Ch5");
                serXML.startTag(null, "Ch6");
                serXML.text(ecgDataMaps.get("Ch6"));
                serXML.endTag(null, "Ch6");
                serXML.startTag(null, "Ch7");
                serXML.text(ecgDataMaps.get("Ch7"));
                serXML.endTag(null, "Ch7");
                serXML.startTag(null, "Ch8");
                serXML.text(ecgDataMaps.get("Ch8"));
                serXML.endTag(null, "Ch8");
                serXML.startTag(null, "Ch9");
                serXML.text(ecgDataMaps.get("Ch9"));
                serXML.endTag(null, "Ch9");
                serXML.startTag(null, "Ch10");
                serXML.text(ecgDataMaps.get("Ch10"));
                serXML.endTag(null, "Ch10");
                serXML.startTag(null, "Ch11");
                serXML.text(ecgDataMaps.get("Ch11"));
                serXML.endTag(null, "Ch11");
            }
            serXML.startTag(null, "Parameter");
            serXML.attribute(null, "RRInterval", ecgAttr.get("RRInterval"));
            serXML.attribute(null, "Gain", ecgAttr.get("Gain"));
            serXML.attribute(null, "Speed", ecgAttr.get("Speed"));
            serXML.attribute(null, "DisplayType", ecgAttr.get("DisplayType"));
            serXML.attribute(null,"HeartRate", ecgAttr.get("HeartRate"));
            serXML.attribute(null, "PRInterval", ecgAttr.get("PRInterval"));
            serXML.attribute(null, "QRSDuration", ecgAttr.get("QRSDuration"));
            serXML.attribute(null, "QTD", ecgAttr.get("QTD"));
            serXML.attribute(null, "QTC", ecgAttr.get("QTC"));
            serXML.attribute(null, "PAxis", ecgAttr.get("PAxis"));
            serXML.attribute(null, "QRSAxis", ecgAttr.get("QRSAxis"));
            serXML.attribute(null, "TAxis", ecgAttr.get("TAxis"));
            serXML.attribute(null, "RV5SV1", ecgAttr.get("RV5SV1"));
            serXML.attribute(null, "RV5", ecgAttr.get("RV5"));
            serXML.attribute(null, "SV1", ecgAttr.get("SV1"));
            serXML.endTag(null, "Parameter");

            if (ecgAttr.containsKey("Auto_Result")) {
                String result = ecgAttr.get("Auto_Result");
                serXML.startTag(null, "AnalysisResult");
                try {
                    Iterator<Map.Entry<String, String>> itClass = ECGDataUtil.decodeEcgResult(result).getClassfy().entrySet().iterator();
                    Map.Entry<String, String> mapClass = itClass.next();
                    serXML.startTag(null, "Classfly");
                    serXML.attribute(null, "Code", mapClass.getKey());
                    serXML.text(mapClass.getValue());
                    serXML.endTag(null, "Classfly");
                    Iterator<Map.Entry<String, String>> itResut = ECGDataUtil.decodeEcgResult(result).getResult().entrySet().iterator();
                    while (itResut.hasNext()) {
                        Map.Entry<String, String> itMap = itResut.next();
                        serXML.startTag(null, "Result");
                        serXML.attribute(null, "Code", itMap.getKey());
                        serXML.text(itMap.getValue());
                        serXML.endTag(null, "Result");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    serXML.startTag(null, "Classfly");
                    serXML.attribute(null, "Code", "0");
                    serXML.text("分析失败");
                    serXML.endTag(null, "Classfly");
                    serXML.startTag(null, "Result");
                    serXML.attribute(null, "Code", "0");
                    serXML.text("分析失败");
                    serXML.endTag(null, "Result");
                }
                serXML.endTag(null, "AnalysisResult");
            }
            serXML.endTag(null, "ECG");
            serXML.endDocument();
            fos.flush();
            fos.close();
        } catch (IllegalArgumentException | IllegalStateException | IOException e) {
            e.printStackTrace();
            Log.e("TAG", "xml:" + e.getMessage());
        }
        return path;
    }


    /**
     * 将byte数组的内容写入到文件
     */
    public static void saveByteArrayToFile(String fileName, byte[] buffer) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName, true);
            fos.write(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将文件中的内容读到byte数组中
     */
    public static byte[] readByteArray(String fileName, int position, int length) {
        byte[] buffer = new byte[position];
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(fileName);
            fis.read(buffer, position, length);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer;
    }

    /**
     * 将12导的数据分别保存成 text
     * 0:I; 1:II; 2:III; 3:aVR; 4:aVL 5:aVF; 6:v1; 7:v2; 8:v3; 9:v4; 10:v5; 11:v6
     **/
    public static void save12EcgDataToInt(String path, long ecg2Device_time, Map<Integer, int[]> datas) {
        if (ecg2Device_time < 0) {
            return;
        }
        File fileV1 = new File(path + "v1.txt");
        File fileV2 = new File(path + "v2.txt");
        File fileV3 = new File(path + "v3.txt");
        File fileV4 = new File(path + "v4.txt");
        File fileV5 = new File(path + "v5.txt");
        File fileV6 = new File(path + "v6.txt");
        File fileAVF = new File(path + "avf.txt");
        File fileAVL = new File(path + "avl.txt");
        File fileAVR = new File(path + "avr.txt");
        File fileI = new File(path + "i.txt");
        File fileII = new File(path + "ii.txt");
        File fileIII = new File(path + "iii.txt");
        saveByteArrayToFile(fileI.getAbsolutePath(), toByteArray(datas.get(0)));
        saveByteArrayToFile(fileII.getAbsolutePath(), toByteArray(datas.get(1)));
        saveByteArrayToFile(fileIII.getAbsolutePath(), toByteArray(datas.get(2)));
        saveByteArrayToFile(fileAVR.getAbsolutePath(), toByteArray(datas.get(3)));
        saveByteArrayToFile(fileAVL.getAbsolutePath(), toByteArray(datas.get(4)));
        saveByteArrayToFile(fileAVF.getAbsolutePath(), toByteArray(datas.get(5)));
        saveByteArrayToFile(fileV1.getAbsolutePath(), toByteArray(datas.get(6)));
        saveByteArrayToFile(fileV2.getAbsolutePath(), toByteArray(datas.get(7)));
        saveByteArrayToFile(fileV3.getAbsolutePath(), toByteArray(datas.get(8)));
        saveByteArrayToFile(fileV4.getAbsolutePath(), toByteArray(datas.get(9)));
        saveByteArrayToFile(fileV5.getAbsolutePath(), toByteArray(datas.get(10)));
        saveByteArrayToFile(fileV6.getAbsolutePath(), toByteArray(datas.get(11)));
    }

    /**
     * 0:I; 1:II; 2:III; 3:aVR; 4:aVL 5:aVF; 6:v1; 7:v2; 8:v3; 9:v4; 10:v5; 11:v6
     * 将12导的数据分别保存成 text
     **/
    public static void save12EcgDataToIntIntegers(String path, long ecg2Device_time, Map<Integer, Integer[]> dataMap) {
        if (ecg2Device_time < 0) {
            return;
        }
        File fileV1 = new File(path + ecg2Device_time + "_v1.txt");
        File fileV2 = new File(path + ecg2Device_time + "_v2.txt");
        File fileV3 = new File(path + ecg2Device_time + "_v3.txt");
        File fileV4 = new File(path + ecg2Device_time + "_v4.txt");
        File fileV5 = new File(path + ecg2Device_time + "_v5.txt");
        File fileV6 = new File(path + ecg2Device_time + "_v6.txt");
        File fileAVF = new File(path + ecg2Device_time + "_avf.txt");
        File fileAVL = new File(path + ecg2Device_time + "_avl.txt");
        File fileAVR = new File(path + ecg2Device_time + "_avr.txt");
        File fileI = new File(path + ecg2Device_time + "_i.txt");
        File fileII = new File(path + ecg2Device_time + "_ii.txt");
        File fileIII = new File(path + ecg2Device_time + "_iii.txt");
        saveByteArrayToFile(fileI.getAbsolutePath(), toByteArray(dataMap.get(0)));
        saveByteArrayToFile(fileII.getAbsolutePath(), toByteArray(dataMap.get(1)));
        saveByteArrayToFile(fileIII.getAbsolutePath(), toByteArray(dataMap.get(2)));
        saveByteArrayToFile(fileAVR.getAbsolutePath(), toByteArray(dataMap.get(3)));
        saveByteArrayToFile(fileAVL.getAbsolutePath(), toByteArray(dataMap.get(4)));
        saveByteArrayToFile(fileAVF.getAbsolutePath(), toByteArray(dataMap.get(5)));
        saveByteArrayToFile(fileV1.getAbsolutePath(), toByteArray(dataMap.get(6)));
        saveByteArrayToFile(fileV2.getAbsolutePath(), toByteArray(dataMap.get(7)));
        saveByteArrayToFile(fileV3.getAbsolutePath(), toByteArray(dataMap.get(8)));
        saveByteArrayToFile(fileV4.getAbsolutePath(), toByteArray(dataMap.get(9)));
        saveByteArrayToFile(fileV5.getAbsolutePath(), toByteArray(dataMap.get(10)));
        saveByteArrayToFile(fileV6.getAbsolutePath(), toByteArray(dataMap.get(11)));
    }


    public static ECGData parserLongEcgData(String path) {
        ECGData ecgData = null;
        File file = new File(path);
        try {
            InputStream inputStream = new FileInputStream(file);
            ecgData = parserLongEcgData(inputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return ecgData;
    }

    public static ECGData parserLongEcgData(InputStream is) {
        ECGData ecgData = new ECGData();
        ECGDataUtil.ECGDataResultHelper resultHelper = new ECGDataUtil.ECGDataResultHelper();
        boolean isfirst = false;//判断是否是最后DMData里的心电数据
        try {
            XmlPullParserFactory pullFactory = XmlPullParserFactory.newInstance();
            XmlPullParser pullParser = pullFactory.newPullParser();
            pullParser.setInput(is, "UTF-8");
            int eventType = pullParser.getEventType();
            while (XmlPullParser.END_DOCUMENT != eventType) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
//					Log.i("FileScan", "标签名称 :  "+pullParser.getName());
                        if ("DMData".equals(pullParser.getName())) {
                            isfirst = true;
                        }
                        if ("Ch0".equals(pullParser.getName()) && !isfirst) {// I
                            String Ch0_I = pullParser.nextText();
                            Log.i("FileScan", "name : " + pullParser.getName() + "value ： " + Ch0_I);
                            short array[] = UnicodeStringtoByte.StringToByte(Ch0_I);
                            Log.i("FileScan", "len is " + String.valueOf(array.length));
                            ecgData.setvI(ZipUtil.gZip(toByteArray(array)));
                        }
                        if ("Ch1".equals(pullParser.getName()) && !isfirst) {// II
                            String Ch1_II = pullParser.nextText();
                            Log.i("FileScan", "name : " + pullParser.getName() + "value ： " + Ch1_II);
                            ecgData.setvII(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.StringToByte(Ch1_II))));
                        }
                        if ("Ch2".equals(pullParser.getName()) && !isfirst) {// III
                            String Ch2_III = pullParser.nextText();
                            Log.i("FileScan", "name : " + pullParser.getName() + "value ： " + Ch2_III);
                            ecgData.setvIII(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.StringToByte(Ch2_III))));
                        }
                        if ("Ch3".equals(pullParser.getName()) && !isfirst) {// avR
                            String Ch3_avR = pullParser.nextText();
                            Log.i("FileScan", "name : " + pullParser.getName() + "value ： " + Ch3_avR);
                            ecgData.setaVr(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.StringToByte(Ch3_avR))));
                        }
                        if ("Ch4".equals(pullParser.getName()) && !isfirst) {// avL
                            String Ch4_avL = pullParser.nextText();
                            Log.i("FileScan", "name : " + pullParser.getName() + "value ： " + Ch4_avL);
                            ecgData.setaVl(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.StringToByte(Ch4_avL))));
                        }
                        if ("Ch5".equals(pullParser.getName()) && !isfirst) {// avF
                            String Ch5_avF = pullParser.nextText();
                            Log.i("FileScan", "name : " + pullParser.getName() + "value ： " + Ch5_avF);
                            ecgData.setaVf(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.StringToByte(Ch5_avF))));
                        }
                        if ("Ch6".equals(pullParser.getName()) && !isfirst) {// v1
                            String Ch6_v1 = pullParser.nextText();
                            Log.i("FileScan", "name : " + pullParser.getName() + "value ： " + Ch6_v1);
                            ecgData.setV1(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.StringToByte(Ch6_v1))));
                        }
                        if ("Ch7".equals(pullParser.getName()) && !isfirst) {// v2
                            String Ch7_v2 = pullParser.nextText();
                            Log.i("FileScan", "name : " + pullParser.getName() + "value ： " + Ch7_v2);
                            ecgData.setV2(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.StringToByte(Ch7_v2))));
                        }
                        if ("Ch8".equals(pullParser.getName()) && !isfirst) {// v3
                            String Ch8_v3 = pullParser.nextText();
                            Log.i("FileScan", "name : " + pullParser.getName() + "value ： " + Ch8_v3);
                            ecgData.setV3(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.StringToByte(Ch8_v3))));
                        }
                        if ("Ch9".equals(pullParser.getName()) && !isfirst) {// v4
                            String Ch9_v4 = pullParser.nextText();
                            Log.i("FileScan", "name : " + pullParser.getName() + "value ： " + Ch9_v4);
                            ecgData.setV4(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.StringToByte(Ch9_v4))));
                        }
                        if ("Ch10".equals(pullParser.getName()) && !isfirst) {// v5
                            String Ch10_v5 = pullParser.nextText();
                            Log.i("FileScan", "name : " + pullParser.getName() + "value ： " + Ch10_v5);
                            ecgData.setV5(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.StringToByte(Ch10_v5))));
                        }
                        if ("Ch11".equals(pullParser.getName()) && !isfirst) {// v6
                            String Ch11_v6 = pullParser.nextText();
                            Log.i("FileScan", "name : " + pullParser.getName() + "value ： " + Ch11_v6);
                            ecgData.setV6(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.StringToByte(Ch11_v6))));
                        }
                        if ("Parameter".equals(pullParser.getName())) {
                            Log.i("FileScan", "HeartRate ： " + pullParser.getAttributeValue(null, "HeartRate"));
                            ecgData.setHeartRate(Integer.valueOf(pullParser.getAttributeValue(null, "HeartRate")));
                        }
//					if ("ResultString".equals(pullParser.getName())) {
//						String ResCode = pullParser.nextText();
//						Log.i("FileScan", "name : "+pullParser.getName()+"value ： "+ ResCode);
//						ecgData.setAutoDiagnosisResult(ResCode);
//					}
                        if ("Classfly".equals(pullParser.getName())) {
                            String classCode = pullParser.getAttributeValue(null, "Code");
                            String className = pullParser.nextText();
                            resultHelper.getClassfy().put(classCode, className);
                        }
                        if ("Result".equals(pullParser.getName())) {
                            String resultCode = pullParser.getAttributeValue(null, "Code");
                            String resultName = pullParser.nextText();
                            resultHelper.getResult().put(resultCode, resultName);
                        }
                        if ("WaveQuality".equals(pullParser.getName())) {
                            String waveQuality = pullParser.nextText();
                            if (!TextUtils.isEmpty(waveQuality)) {
                                ecgData.setDoctorComment(waveQuality);
                            }
                        }

                        //<Parameter AnalysisState="1" PWidth="49" PExist="1" RRInterval="0" HeartRate="80" PRInterval="82"
                        //QRSDuration="48" QTD="178" QTC="205" PAxis="18" QRSAxis="18" TAxis="17" RV5V6="0.000" SV1V2="0.000"
                        //RV1SV5="0.000" RV5SV1="1583.0001" RV5="1172.0" SV1="-411.0">
                        break;
                    case XmlPullParser.END_TAG:
                        if (pullParser.getName().equals("ECG")) {
                            Log.i("FileScan", "解析完毕");
                        }
                        break;
                    default:
                        break;
                }
                eventType = pullParser.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        String autoResult = ECGDataUtil.encodeEcgResult(resultHelper);
        ecgData.setAutoDiagnosisResult(autoResult);
        return ecgData;
    }

    /**
     * 根据路径获取华清心仪测量后的数据
     * 并解析成ECGData
     *
     * @param path
     * @return
     */
    public static ECGData preparseECGData(String path) {
        ECGData ecgData = null;
        ECGDataUtil.ECGDataResultHelper resultHelper = new ECGDataUtil.ECGDataResultHelper();
        File file = new File(path);
        try {
            InputStream inputStream = new FileInputStream(file);
            XmlPullParserFactory pullFactory = XmlPullParserFactory.newInstance();
            XmlPullParser pullParser = pullFactory.newPullParser();
            pullParser.setInput(inputStream, "UTF-8");
            int eventType = pullParser.getEventType();
            ecgData = new ECGData();
            ecgData.setVersion(1);
            while (XmlPullParser.END_DOCUMENT != eventType) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        if ("ECG".equals(pullParser.getName())) {
                            ecgData.setFnotch(pullParser.getAttributeValue(null, "FNotch"));
                            ecgData.setFhp(pullParser.getAttributeValue(null, "FHP"));
                            ecgData.setFlp(pullParser.getAttributeValue(null, "FLP"));
                        }
                        if ("Name".equals(pullParser.getName())) {
                            ecgData.setPatiName(pullParser.nextText());
                        }
                        if ("ID".equals(pullParser.getName())) {
                            ecgData.setPatientId(pullParser.nextText());
                        }
                        if ("CheckDateTime".equals(pullParser.getName())) {
                            String time = pullParser.nextText();
                            Date date = null;
                            try {
                                date = DateUtil.sdf_yyyy_MM_dd_HH_mm_ss.parse(time);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            ecgData.setTime(date);
                        }
                        if ("Ch0".equals(pullParser.getName())) {// I
                            String Ch0_I = pullParser.nextText();
                            int array[] = UnicodeStringtoByte.string2Int(Ch0_I);
                            ecgData.setvI(ZipUtil.gZip(toByteArray(array)));
                        }
                        if ("Ch1".equals(pullParser.getName())) {// II
                            String Ch1_II = pullParser.nextText();
                            ecgData.setvII(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.string2Int(Ch1_II))));
                        }
                        if ("Ch2".equals(pullParser.getName())) {// III
                            String Ch2_III = pullParser.nextText();
                            ecgData.setvIII(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.string2Int(Ch2_III))));
                        }
                        if ("Ch3".equals(pullParser.getName())) {// avR
                            String Ch3_avR = pullParser.nextText();
                            ecgData.setaVr(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.string2Int(Ch3_avR))));
                        }
                        if ("Ch4".equals(pullParser.getName())) {// avL
                            String Ch4_avL = pullParser.nextText();
                            ecgData.setaVl(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.string2Int(Ch4_avL))));
                        }
                        if ("Ch5".equals(pullParser.getName())) {// avF
                            String Ch5_avF = pullParser.nextText();
                            ecgData.setaVf(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.string2Int(Ch5_avF))));
                        }
                        if ("Ch6".equals(pullParser.getName())) {// v1
                            String Ch6_v1 = pullParser.nextText();
                            ecgData.setV1(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.string2Int(Ch6_v1))));
                        }
                        if ("Ch7".equals(pullParser.getName())) {// v2
                            String Ch7_v2 = pullParser.nextText();
                            ecgData.setV2(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.string2Int(Ch7_v2))));
                        }
                        if ("Ch8".equals(pullParser.getName())) {// v3
                            String Ch8_v3 = pullParser.nextText();
                            ecgData.setV3(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.string2Int(Ch8_v3))));
                        }
                        if ("Ch9".equals(pullParser.getName())) {// v4
                            String Ch9_v4 = pullParser.nextText();
                            ecgData.setV4(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.string2Int(Ch9_v4))));
                        }
                        if ("Ch10".equals(pullParser.getName())) {// v5
                            String Ch10_v5 = pullParser.nextText();
                            ecgData.setV5(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.string2Int(Ch10_v5))));
                        }
                        if ("Ch11".equals(pullParser.getName())) {// v6
                            String Ch11_v6 = pullParser.nextText();
                            ecgData.setV6(ZipUtil.gZip(toByteArray(UnicodeStringtoByte.string2Int(Ch11_v6))));
                        }
                        if ("Parameter".equals(pullParser.getName())) {
                            ecgData.setHeartRate(Integer.valueOf(pullParser.getAttributeValue(null, "HeartRate")));
                            ecgData.setPr(Integer.valueOf(pullParser.getAttributeValue(null, "RRInterval")));
                            ecgData.setQrs(Integer.valueOf(pullParser.getAttributeValue(null, "QRSDuration")));
                            ecgData.setQtc(Integer.valueOf(pullParser.getAttributeValue(null, "QTC")));
                            ecgData.setQt(Integer.valueOf(pullParser.getAttributeValue(null, "QTD")));
                            ecgData.setPaxis(Integer.valueOf(pullParser.getAttributeValue(null, "PAxis")));
                            ecgData.setQrsaxis(Integer.valueOf(pullParser.getAttributeValue(null, "QRSAxis")));
                            ecgData.setTaxis(Integer.valueOf(pullParser.getAttributeValue(null, "TAxis")));
                            ecgData.setRv5sv1(Double.valueOf(pullParser.getAttributeValue(null, "RV5SV1")));
                            ecgData.setRv5(Double.valueOf(pullParser.getAttributeValue(null, "RV5")));
                            ecgData.setSv1(Double.valueOf(pullParser.getAttributeValue(null, "SV1")));
                        }
                        if ("Classfly".equals(pullParser.getName())) {
                            String classCode = pullParser.getAttributeValue(null, "Code");
                            String className = pullParser.nextText();
                            resultHelper.getClassfy().put(classCode, className);
                        }
                        if ("Result".equals(pullParser.getName())) {
                            String resultCode = pullParser.getAttributeValue(null, "Code");
                            String resultName = pullParser.nextText();
                            resultHelper.getResult().put(resultCode, resultName);
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if (pullParser.getName().equals("ECG")) {
                            Log.i("FileScan", "解析完毕");
                        }
                        break;
                    default:
                        break;
                }
                eventType = pullParser.next();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (ecgData != null) {
            resultHelper.setDiagnosisType(ECGDataDiagnosisType.auto.ordinal());
            String autoResult = ECGDataUtil.encodeEcgResult(resultHelper);
            ecgData.setAutoDiagnosisResult(autoResult);
        }

        return ecgData;
    }

    public static ECGData parse2Data(String path) {
        ECGData ecgData = null;
        ECGDataUtil.ECGDataResultHelper resultHelper = new ECGDataUtil.ECGDataResultHelper();
        File file = new File(path);
         try {
            InputStream inputStream = new FileInputStream(file);
            XmlPullParserFactory pullFactory = XmlPullParserFactory.newInstance();
            XmlPullParser pullParser = pullFactory.newPullParser();
            pullParser.setInput(inputStream, "UTF-8");
            int eventType = pullParser.getEventType();
            ecgData = new ECGData();
            ecgData.setVersion(1);
            while (XmlPullParser.END_DOCUMENT != eventType) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        if ("ECG".equals(pullParser.getName())) {
                            ecgData.setFnotch(pullParser.getAttributeValue(null, "FNotch"));
                            ecgData.setFhp(pullParser.getAttributeValue(null, "FHP"));
                            ecgData.setFlp(pullParser.getAttributeValue(null, "FLP"));
                        }
                        if ("Name".equals(pullParser.getName())) {
                            ecgData.setPatiName(pullParser.nextText());
                        }
                        if ("ID".equals(pullParser.getName())) {
                            ecgData.setCellphone(pullParser.nextText());
                        }
                        if ("Age".equals(pullParser.getName())) {
                            try {
                                ecgData.setAge(Integer.parseInt(pullParser.nextText()));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        if ("Gender".equals(pullParser.getName())) {
                            try {
                                ecgData.setGender(Integer.parseInt(pullParser.nextText()));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        if ("CheckDateTime".equals(pullParser.getName())) {
                            String time = pullParser.nextText();
                            Date date = null;
                            try {
                                date = DateUtilssss.sdf_yyyy_MM_dd_HH_mm_ss.parse(time);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            ecgData.setTime(date);
                        }
                        if ("Ch0".equals(pullParser.getName())) {// I
                            String Ch0_I = pullParser.nextText();
                            int[] array = UnicodeStringtoByte.string2Int(Ch0_I);
                            ecgData.setvI(ZipUtil.gZip(DateUtilssss.toByteArray(array)));
                        }
                        if ("Ch1".equals(pullParser.getName())) {// II
                            String Ch1_II = pullParser.nextText();
                            ecgData.setvII(ZipUtil.gZip(DateUtilssss.toByteArray(UnicodeStringtoByte.string2Int(Ch1_II))));
                        }
                        if ("Ch2".equals(pullParser.getName())) {// III
                            String Ch2_III = pullParser.nextText();
                            ecgData.setvIII(ZipUtil.gZip(DateUtilssss.toByteArray(UnicodeStringtoByte.string2Int(Ch2_III))));
                        }
                        if ("Ch3".equals(pullParser.getName())) {// avR
                            String Ch3_avR = pullParser.nextText();
                            ecgData.setaVr(ZipUtil.gZip(DateUtilssss.toByteArray(UnicodeStringtoByte.string2Int(Ch3_avR))));
                        }
                        if ("Ch4".equals(pullParser.getName())) {// avL
                            String Ch4_avL = pullParser.nextText();
                            ecgData.setaVl(ZipUtil.gZip(DateUtilssss.toByteArray(UnicodeStringtoByte.string2Int(Ch4_avL))));
                        }
                        if ("Ch5".equals(pullParser.getName())) {// avF
                            String Ch5_avF = pullParser.nextText();
                            ecgData.setaVf(ZipUtil.gZip(DateUtilssss.toByteArray(UnicodeStringtoByte.string2Int(Ch5_avF))));
                        }
                        if ("Ch6".equals(pullParser.getName())) {// v1
                            String Ch6_v1 = pullParser.nextText();
                            ecgData.setV1(ZipUtil.gZip(DateUtilssss.toByteArray(UnicodeStringtoByte.string2Int(Ch6_v1))));
                        }
                        if ("Ch7".equals(pullParser.getName())) {// v2
                            String Ch7_v2 = pullParser.nextText();
                            ecgData.setV2(ZipUtil.gZip(DateUtilssss.toByteArray(UnicodeStringtoByte.string2Int(Ch7_v2))));
                        }
                        if ("Ch8".equals(pullParser.getName())) {// v3
                            String Ch8_v3 = pullParser.nextText();
                            ecgData.setV3(ZipUtil.gZip(DateUtilssss.toByteArray(UnicodeStringtoByte.string2Int(Ch8_v3))));
                        }
                        if ("Ch9".equals(pullParser.getName())) {// v4
                            String Ch9_v4 = pullParser.nextText();
                            ecgData.setV4(ZipUtil.gZip(DateUtilssss.toByteArray(UnicodeStringtoByte.string2Int(Ch9_v4))));
                        }
                        if ("Ch10".equals(pullParser.getName())) {// v5
                            String Ch10_v5 = pullParser.nextText();
                            ecgData.setV5(ZipUtil.gZip(DateUtilssss.toByteArray(UnicodeStringtoByte.string2Int(Ch10_v5))));
                        }
                        if ("Ch11".equals(pullParser.getName())) {// v6
                            String Ch11_v6 = pullParser.nextText();
                            ecgData.setV6(ZipUtil.gZip(DateUtilssss.toByteArray(UnicodeStringtoByte.string2Int(Ch11_v6))));
                        }
                        if ("Parameter".equals(pullParser.getName())) {
                            ecgData.setHeartRate(Integer.parseInt(pullParser.getAttributeValue(null, "HeartRate")));
                            ecgData.setPr(Integer.parseInt(pullParser.getAttributeValue(null, "PRInterval")));
                            ecgData.setQrs(Integer.parseInt(pullParser.getAttributeValue(null, "QRSDuration")));
                            ecgData.setQtc(Integer.parseInt(pullParser.getAttributeValue(null, "QTC")));
                            ecgData.setQt(Integer.parseInt(pullParser.getAttributeValue(null, "QTD")));
                            ecgData.setPaxis(Integer.parseInt(pullParser.getAttributeValue(null, "PAxis")));
                            ecgData.setQrsaxis(Integer.parseInt(pullParser.getAttributeValue(null, "QRSAxis")));
                            ecgData.setTaxis(Integer.parseInt(pullParser.getAttributeValue(null, "TAxis")));
                            ecgData.setRv5sv1(Double.parseDouble(pullParser.getAttributeValue(null, "RV5SV1")));
                            ecgData.setRv5(Double.parseDouble(pullParser.getAttributeValue(null, "RV5")));
                            ecgData.setSv1(Double.parseDouble(pullParser.getAttributeValue(null, "SV1")));
                            ecgData.setGain(Integer.parseInt(pullParser.getAttributeValue(null, "Gain")));
                            ecgData.setSpeed(Integer.parseInt(pullParser.getAttributeValue(null, "Speed")));
                            ecgData.setDisplayType(Integer.parseInt(pullParser.getAttributeValue(null, "DisplayType")));
                        }
                        if ("Classfly".equals(pullParser.getName())) {
                            String classCode = pullParser.getAttributeValue(null, "Code");
                            String className = pullParser.nextText();
                            resultHelper.getClassfy().put(classCode, className);
                        }
                        if ("Result".equals(pullParser.getName())) {
                            String resultCode = pullParser.getAttributeValue(null, "Code");
                            String resultName = pullParser.nextText();
                            resultHelper.getResult().put(resultCode, resultName);
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if (pullParser.getName().equals("ECG")) {
                            Log.i("FileScan", "解析完毕");
                        }
                        break;
                    default:
                        break;
                }
                eventType = pullParser.next();
            }
        } catch (XmlPullParserException | IOException e) {
            e.printStackTrace();
        }
        if (ecgData != null) {
            resultHelper.setDiagnosisType(ECGDataDiagnosisType.auto.ordinal());
            String autoResult = ECGDataUtil.encodeEcgResult(resultHelper);
            ecgData.setAutoDiagnosisResult(autoResult);
        }
        return ecgData;
    }


    public static ECGData gZip(ECGData from) {
        from.setV1(ZipUtil.gZip(from.getV1()));
        from.setV2(ZipUtil.gZip(from.getV2()));
        from.setV3(ZipUtil.gZip(from.getV3()));
        from.setV4(ZipUtil.gZip(from.getV4()));
        from.setV5(ZipUtil.gZip(from.getV5()));
        from.setV6(ZipUtil.gZip(from.getV6()));
        from.setvI(ZipUtil.gZip(from.getvI()));
        from.setvII(ZipUtil.gZip(from.getvII()));
        from.setvIII(ZipUtil.gZip(from.getvIII()));
        from.setaVr(ZipUtil.gZip(from.getaVr()));
        from.setaVl(ZipUtil.gZip(from.getaVl()));
        from.setaVf(ZipUtil.gZip(from.getaVf()));
        return from;
    }


    public static ECGData ungZip(ECGData from) {
        try {
            from.setV1(ZipUtil.unGZip(from.getV1()));
            from.setV2(ZipUtil.unGZip(from.getV2()));
            from.setV3(ZipUtil.unGZip(from.getV3()));
            from.setV4(ZipUtil.unGZip(from.getV4()));
            from.setV5(ZipUtil.unGZip(from.getV5()));
            from.setV6(ZipUtil.unGZip(from.getV6()));
            from.setvI(ZipUtil.unGZip(from.getvI()));
            from.setvII(ZipUtil.unGZip(from.getvII()));
            from.setvIII(ZipUtil.unGZip(from.getvIII()));
            from.setaVr(ZipUtil.unGZip(from.getaVr()));
            from.setaVl(ZipUtil.unGZip(from.getaVl()));
            from.setaVf(ZipUtil.unGZip(from.getaVf()));
        } catch (Exception e) {
            System.out.println("Not in GZip Format");
            return from;
        }
        return from;
    }

}
